<?php

namespace common\model;

use think\Hook;
use think\model\RelationModel;

class TenantUserModel extends RelationModel
{
    const STATUS_ACTIVE = 'active'; // 激活
    const STATUS_INVALID = 'invalid'; // 非法
    const STATUS_UNEMPLOYED = 'unemployed'; // 离职
    //自动验证
    protected $_validate = [
        ['user_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['tenant_id', '', '', self::MUST_VALIDATE, 'require', self::MODEL_INSERT],//必须字段
        ['user_id,tenant_id', '', '', self::MUST_VALIDATE, 'unique'],
        ['status', ['active', 'invalid', 'unemployed'], '', self::EXISTS_VALIDATE, 'in']
    ];

    // 自动完成
    protected $_auto = [
        ['created', 'time', self::MODEL_INSERT, 'function']
    ];

    /**
     * 获取器：创建时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getCreatedAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }

    /**
     * @inheritDoc
     */
    public function _after_update($result, $pkName, $data, $options, $writeEvent)
    {
        parent::_after_update($result, $pkName, $data, $options, $writeEvent);
        $param = [
            'level' => 'info',
            'operate' => 'update',
            'primary_id' => $this->oldUpdateKey,
            'primary_field' => $pkName,
            'data' => ["old" => $this->oldUpdateData, "new" => $this->newUpdateData],
            'param' => $options,
            'table' => $this->getTableName()
        ];
        Hook::listen('after_tenant_user_updated', $param);
    }
}
